package com.creditease.shield.flow.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.internal.PlatformDependent;

public abstract class NettyServerAcceptor implements ServerAcceptor{
	
	public static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
	
	protected EventLoopGroup bossGroup;
    protected EventLoopGroup workerGroup;
    protected ServerBootstrap serverBootstrap;
    
    protected volatile ByteBufAllocator allocator;
	
	protected void init(){
		 bossGroup = new NioEventLoopGroup(1);
         workerGroup = new NioEventLoopGroup(AVAILABLE_PROCESSORS << 1);
         /**
          * 一般高性能的场景下,使用的堆外内存，也就是直接内存，使用堆外内存的好处就是减少内存的拷贝，和上下文的切换，缺点是
          * 堆外内存处理的不好容易发生堆外内存OOM
          * 当然也要看当前的JVM是否只是使用堆外内存，换而言之就是是否能够获取到Unsafe对象#PlatformDependent.directBufferPreferred()
          */
         allocator = new PooledByteBufAllocator(PlatformDependent.directBufferPreferred());
         //create && group
         serverBootstrap = new ServerBootstrap().group(bossGroup, workerGroup);
         //ByteBufAllocator 配置
         serverBootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
         
	}

}
